﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows.Threading;

namespace AnimationAdditions
{
	public class PreviewObservableCollection<T> : ObservableCollection<T>, IPreviewCollection
	{
		public PreviewObservableCollection(Dispatcher dispatcher, IEnumerable<T> items) : base(items)
		{
			this.dispatcher = dispatcher;
		}

		public event EventHandler<PreviewDeleteEventArgs> PreviewDelete;

		protected void OnPreviewDelete(PreviewDeleteEventArgs e)
		{
			var local = PreviewDelete;
			if (local != null)
			{
				local.BeginInvoke(this, e, PreviewDeleteCompleted, e.Index);
			}
		}

		private void PreviewDeleteCompleted(IAsyncResult ar)
		{
			dispatcher.Invoke(new Action(() =>
				base.RemoveItem((int) ar.AsyncState)));
		}

		protected override void RemoveItem(int index)
		{
			var args = new PreviewDeleteEventArgs(Items[index], index);
			OnPreviewDelete(args);
		}

		private readonly Dispatcher dispatcher;
	}
}